<%@ page import="java.sql.*" %><%--
 <% %>定义 局部变量
 <%! %>定义全局变量
 解决乱码的四种方式
 <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<% request.setCharacterEncoding("utf8");response.setCharacterEncoding("utf8");%>
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    request.setCharacterEncoding("utf8");
    String username=request.getParameter("username");
    String password=request.getParameter("password");

    final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    final String DBURL = "jdbc:mysql://127.0.0.1:3306/javaweb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
    final String DBUSER = "root";
    final String DBPASS = "root";

    Connection conn;
    PreparedStatement ps;
    ResultSet rs;
    if (!("".equals(username)&&username!=null&&"".equals(password)&&password!=null)){

        try{
            Class.forName(DBDRIVER);
            conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);

            /**
             * 添加用户数据到数据库中
             */
            ps = conn.prepareStatement(
                    "select password from user where username=? and password=?");
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();


            if (rs.next()) {
                Cookie cookie = new Cookie("username", username);
                cookie.setMaxAge(60 * 60 * 5);//以秒为单位(这里设置为保留5小时)
                Cookie cookie1 = new Cookie("password", password);
                cookie1.setMaxAge(60 * 60 * 5);//以秒为单位
                response.addCookie(cookie);
                response.addCookie(cookie1);
                HttpSession session1 = request.getSession();
                session1.setAttribute("username", username);
                session1.setAttribute("password", password);
                rs.close();
                ps.close();
                conn.close();

                response.sendRedirect("survey.jsp");
%>

<%
} else{%><jsp:forward page="failed.jsp"></jsp:forward><% }}catch (SQLException e){out.println(e.toString());}}else {%>
<jsp:forward page="failed.jsp"></jsp:forward>
<%}%>
</body>
</html>
